package tictactoe;

import tictactoe.protocol.Protocol;

import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Double
 * Date: 15.01.12
 * Time: 20:55
 * To change this template use File | Settings | File Templates.
 */
public class Client implements Runnable
{
	private String name;
	private int wins=0;
	transient private int figure; // 0 - circle, 1 - lines
	transient private boolean turnFlag = false;
	transient private Socket s;
	transient private InputStream is;
	transient private OutputStream os;
	transient private BufferedReader in = null;
	transient private boolean isPlaying;
	transient private boolean flag=true;

	public boolean isTurnFlag() {
		return turnFlag;
	}

	public void setTurnFlag(boolean turnFlag) {
		this.turnFlag = turnFlag;
	}



	public boolean isPlaying() {
		return isPlaying;
	}

	public void setPlaying(boolean playing) {
		isPlaying = playing;
	}

	public int getFigure() {
		return figure;
	}

	public void setFigure(int figure) {
		this.figure = figure;
	}

	public String getName() {
		return name;
	}

	public synchronized void setName(String name) {
		this.name = name;
		System.out.println(name);
	}

	public Client()
	{
	}

	public Client(Socket accept) {
		s = accept;
		try {
			os = s.getOutputStream();
			is = s.getInputStream();
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			//s.setKeepAlive(true);
		} catch (IOException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		}
		System.out.println("Client created"+s.toString());
		Logger.getLogger("TicTacToeServer").log(Level.SEVERE,"Client thread started: "+s.toString());
	}


	@Override
	public String toString() {
		return "{\\\"name\\\":\\\""+name+"\\\", \\\"wins\\\":"+wins+"}";
	}

	public synchronized void sendMsg(String s)
	{
		System.out.println("To "+name+": "+s);
		Logger.getLogger("TicTacToeServer").log(Level.SEVERE,"To "+name+": "+s);

		try
		{
			os.write(s.getBytes());
		} catch (IOException e)
		{
			//e.printStackTrace();
			Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+":"+e.getMessage());

		}catch (NullPointerException e)
		{
			//e.printStackTrace();
			Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+":"+e.getMessage());
		}
	}
	public void disconnect() throws IOException {
		is.close();
		os.close();
		in.close();
		s.close();
		Server.getClientProcessor().getClients().remove(this);
		System.out.println("Client disconnected.");
		Logger.getLogger("TicTacToeServer").log(Level.SEVERE,"Client disconnected: "+this.getName());

	}

	public boolean isFlag()
	{
		return flag;
	}

	public void setFlag(boolean flag)
	{
		this.flag = flag;
	}

	@Override
	public void run() {
		if(s.isConnected())
		{

			String fromClient=null;
			try {
				while (flag) {
					//Отображаем полученное сообщение
					if(hasMessage())
					{
						fromClient = getMessage();
						System.out.println(name+": " + fromClient);
						Protocol.decodeSystemPacket(fromClient,this,Server.getClientProcessor().getClients());
						Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+": "+fromClient);
					}

				}
				//disconnect();
			}
			catch (NullPointerException e)
			{
				e.printStackTrace();

			}
		}
	}

	public synchronized boolean hasMessage()
	{

		boolean ret = false;

		//System.out.println(in.ready());
		try
		{
			if(in.ready())
			{
				ret = true;
			}
			else
			{
				ret = false;
			}
		} catch (IOException e)
		{
			e.printStackTrace();
			Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+":"+e.getMessage());
		}
		if(disconnected())
		{
			try
			{
				disconnect();
			} catch (IOException e)
			{
				e.printStackTrace();
				Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+":"+e.getMessage());
			}
		}
		return ret;
	}
	public synchronized String getMessage()
	{
		String ret=null;
		if(!disconnected()){


			try
			{
				ret = in.readLine();
				Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+": "+ret);
			} catch (IOException e)
			{
				e.printStackTrace();
				Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+":"+e.getMessage());
				try
				{
					disconnect();
				} catch (IOException e1)
				{
					e1.printStackTrace();
					Logger.getLogger("TicTacToeServer").log(Level.SEVERE,name+":"+e.getMessage());
				}
			}
		}

		return ret;
	}
	public boolean disconnected()
	{
		return s.isClosed();
	}
}
